$(function () {
    var layer = layui.layer;
    var form = layui.form;
    initArtList();
    function initArtList() {
        $.ajax({
            method: 'GET',
            url: '/my/article/cates',
            success: function (res) {
                // console.log(res);
                if (res.status !== 0) {
                    return layer.msg('获取数据失败');
                }
                var htmlStr = template('tpl-cate', res);
                $('select').html(htmlStr);
                form.render();
            }
        });
    }
    initEditor();

    // 1. 初始化图片裁剪器
    var $image = $('#image')

    // 2. 裁剪选项
    var options = {
        aspectRatio: 400 / 280,
        preview: '.img-preview'
    }

    // 3. 初始化裁剪区域
    $image.cropper(options)


    $('#btnChooseImage').on('click', function () {
        $('input[type=file]').click();
    });

    $('input[type=file]').on('change', function (e) {
        var files = e.target.files;
        if (files.length === 0) {
            return
        }
        var url = URL.createObjectURL(files[0]);

        $image
            .cropper('destroy')
            .attr('src', url)
            .cropper(options);
    });

    var artState = '已发布';
    $('#btnSave1').on('click', function () {
        artState = '已发布';
    });
    $('#btnSave2').on('click', function () {
        artState = '草稿';
    });

    $('#form-pub').on('submit', function (e) {
        e.preventDefault();
        var form = document.querySelector('#form-pub');
        var fd = new FormData(form);
        fd.set('state', artState);
        // fd.forEach(function (item, key) {
        //     console.log(item, key);
        // });
        $image
            .cropper('getCroppedCanvas', {
                width: 400,
                height: 280
            }).toBlob(function (blob) {
                fd.set('cover_img', blob);
                pA(fd)
            });
    });

    function pA(fd) {
        $.ajax({
            method: 'POST',
            url: '/my/article/add',
            data: fd,
            contentType: false,
            processData: false,
            success: function (res) {
                console.log(res);
                if (res.status !== 0) {
                    return layer.msg('发布文章失败！')
                }
                layer.msg('发布文章成功！')
                // 发布文章成功后，跳转到文章列表页面
                location.href = '/article/art_list.html'
            }
        });
    }
});